<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { getWebsiteContentsApi, type WebsiteContentItem } from '~/api/common/login'

defineOptions({
  name: 'ArticleDetail',
})

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const articleDetail = ref<WebsiteContentItem | null>(null)
const coverImage = computed(() => {
  if (!articleDetail.value)
    return ''
  return articleDetail.value.cover_image || (articleDetail.value as any).cover_url || ''
})

// 格式化日期
function formatDate(dateString: string): string {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}

// 获取发布状态文本
function getPublishStatusText(status: number): string {
  const map: Record<number, string> = {
    0: '草稿',
    1: '待审核',
    2: '已发布',
    3: '已删除',
  }
  return map[status] || '未知'
}

// 获取发布状态类型
function getPublishStatusType(status: number): string {
  const map: Record<number, string> = {
    0: 'draft',
    1: 'pending',
    2: 'published',
    3: 'deleted',
  }
  return map[status] || 'unknown'
}

// 获取文章详情 - 通过列表接口获取，然后查找对应的项
async function fetchArticleDetail() {
  const id = Number(route.params.id)
  if (!id) {
    router.push({ name: 'DashboardAnalysis' })
    return
  }

  loading.value = true
  try {
    // 通过列表接口获取所有内容（不传 channel_id 获取所有栏目的数据）
    const response = await getWebsiteContentsApi({})
    if (response.code === 0 && response.data && Array.isArray(response.data)) {
      // 从列表中查找对应的项
      const article = response.data.find((item: WebsiteContentItem) => item.id === id)
      if (article) {
        articleDetail.value = article
      } else {
        // 如果找不到，尝试通过已知的 channel_id 获取（从列表中获取所有不同的 channel_id）
        const channelIds = [...new Set(response.data.map((item: WebsiteContentItem) => item.channel_id))]
        let found = false
        
        for (const channelId of channelIds) {
          try {
            const channelResponse = await getWebsiteContentsApi({ channel_id: channelId })
            if (channelResponse.code === 0 && channelResponse.data && Array.isArray(channelResponse.data)) {
              const article = channelResponse.data.find((item: WebsiteContentItem) => item.id === id)
              if (article) {
                articleDetail.value = article
                found = true
                break
              }
            }
          } catch (e) {
            // 继续尝试下一个 channel_id
          }
        }
        
        if (!found) {
          message.error('未找到该文章')
          router.push({ name: 'DashboardAnalysis' })
        }
      }
    } else {
      message.error('获取文章列表失败')
      router.push({ name: 'DashboardAnalysis' })
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    message.error('获取文章详情失败，请稍后重试')
    router.push({ name: 'DashboardAnalysis' })
  } finally {
    loading.value = false
  }
}

// 返回列表
function handleBack() {
  router.push({ name: 'DashboardAnalysis' })
}

// 编辑文章
function handleEdit() {
  if (articleDetail.value) {
    router.push({ name: 'WebsiteContentEdit', params: { id: articleDetail.value.id } })
  }
}

onMounted(() => {
  fetchArticleDetail()
})
</script>

<template>
  <page-container>
    <div class="article-detail-container">
      <div class="page-header">
        <a-button class="back-btn" @click="handleBack">
          <template #icon>
            <arrow-left-outlined />
          </template>
          返回
        </a-button>
        <h2 class="page-title">文章详情</h2>
        <a-button
          v-if="articleDetail && articleDetail.publish_status !== 2"
          type="primary"
          class="edit-btn"
          @click="handleEdit"
        >
          编辑
        </a-button>
      </div>

      <a-spin :spinning="loading">
        <div v-if="articleDetail" class="detail-content">
          <div class="detail-layout">
            <!-- 左侧：正文内容（70%） -->
            <div class="detail-left">
              <div class="article-header">
                <div class="header-top">
                  <h1 class="article-title">{{ articleDetail.title }}</h1>
                  <span
                    class="status-chip"
                    :class="`status-${getPublishStatusType(articleDetail.publish_status)}`"
                  >
                    {{ getPublishStatusText(articleDetail.publish_status) }}
                  </span>
                </div>
                <div class="article-meta">
                  <span class="meta-item">
                    <span class="meta-label">副标题：</span>
                    <span class="meta-value">{{ articleDetail.subtitle }}</span>
                  </span>
                  <span class="meta-divider">|</span>
                  <span class="meta-item">
                    <span class="meta-label">所属栏目：</span>
                    <span class="meta-value">{{ (articleDetail as any).channel_name || articleDetail.channel_id }}</span>
                  </span>
                  <span class="meta-divider">|</span>
                  <span class="meta-item">
                    <span class="meta-label">作者：</span>
                    <span class="meta-value">{{ articleDetail.author || '-' }}</span>
                  </span>
                  <span class="meta-divider">|</span>
                  <span class="meta-item">
                    <span class="meta-label">发布时间：</span>
                    <span class="meta-value">{{ formatDate(articleDetail.publish_time) }}</span>
                  </span>
                  <span class="meta-divider">|</span>
                  <span class="meta-item">
                    <span class="meta-label">浏览量：</span>
                    <span class="meta-value">{{ articleDetail.view_count || 0 }}</span>
                  </span>
                </div>
              </div>

              <div
                v-if="coverImage"
                class="detail-cover"
              >
                <img :src="coverImage" alt="文章封面">
              </div>
              
              <div class="article-summary">
                <div class="summary-label">内容摘要</div>
                <div class="summary-content">{{ articleDetail.summary || '-' }}</div>
              </div>
              
              <div class="article-body">
                <div class="body-content" v-html="articleDetail.content || '-'"></div>
              </div>
            </div>
            
            <!-- 右侧：文章信息（30%） -->
        
          </div>
        </div>
      </a-spin>
    </div>
  </page-container>
</template>

<style scoped lang="less">
@import './index.css';

.article-detail-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-title {
  flex: 1;
  font-size: 24px;
  font-weight: 600;
  color: #428bca;
  margin: 0;
}

.back-btn {
  border-radius: 4px;
  border-color: #428bca;
  color: #428bca;
  
  &:hover {
    color: #fff;
    background: #428bca;
    border-color: #428bca;
  }
}

.edit-btn {
  background: linear-gradient(135deg, #428bca, #5c9cd6);
  border: none;
  border-radius: 4px;
  min-width: 100px;
  height: 40px;
  font-weight: 500;
  
  &:hover {
    opacity: 0.92;
  }
}

.detail-content {
  width: 100%;
}

.detail-layout {
  display: flex;
  gap: 24px;
  align-items: flex-start;
}

.detail-left {
  flex: 0 0 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  padding: 32px;
}

.detail-right {
  flex: 0 0 30%;
  position: sticky;
  top: 24px;
}

.article-header {
  margin-bottom: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid #e8e8e8;
}

.header-top {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.article-title {
  font-size: 28px;
  font-weight: 700;
  color: #1f2d3d;
  line-height: 1.4;
  margin: 0 0 16px 0;
}

.status-chip {
  padding: 4px 12px;
  border-radius: 999px;
  font-size: 14px;
  font-weight: 600;
  border: 1px solid transparent;

  &.status-draft {
    color: #c48a10;
    border-color: rgba(196, 138, 16, 0.3);
    background: rgba(196, 138, 16, 0.08);
  }

  &.status-pending {
    color: #1890ff;
    border-color: rgba(24, 144, 255, 0.3);
    background: rgba(24, 144, 255, 0.08);
  }

  &.status-published {
    color: #21ba45;
    border-color: rgba(33, 186, 69, 0.3);
    background: rgba(33, 186, 69, 0.08);
  }

  &.status-deleted {
    color: #d93026;
    border-color: rgba(217, 48, 38, 0.3);
    background: rgba(217, 48, 38, 0.08);
  }
}

.detail-cover {
  margin-bottom: 32px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  background: #f5f5f5;

  img {
    display: block;
    width: 100%;
    max-height: 380px;
    object-fit: cover;
  }
}

.article-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  font-size: 14px;
  color: #666;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.meta-label {
  color: #999;
}

.meta-value {
  color: #333;
  font-weight: 500;
}

.meta-divider {
  color: #d9d9d9;
}

.article-summary {
  margin-bottom: 32px;
  padding: 20px;
  background: linear-gradient(135deg, rgba(66, 139, 202, 0.05) 0%, rgba(92, 156, 214, 0.05) 100%);
  border-left: 4px solid #428bca;
  border-radius: 4px;
}

.summary-label {
  font-size: 14px;
  font-weight: 600;
  color: #428bca;
  margin-bottom: 8px;
  display: block;
}

.summary-content {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
}

.article-body {
  margin-top: 32px;
}

.body-content {
  font-size: 16px;
  line-height: 2;
  color: #333;
  word-wrap: break-word;
  text-align: justify;
  
  :deep(img) {
    max-width: 100%;
    height: auto;
    margin: 12px 0;
  }
  
  :deep(p) {
    margin-bottom: 12px;
  }
}

.info-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.card-header {
  padding: 20px 24px;
  background: linear-gradient(135deg, #428bca, #5c9cd6);
  border-bottom: none;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #fff;
  margin: 0;
}

.card-body {
  padding: 24px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.info-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.info-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  text-align: right;
  max-width: 60%;
  word-break: break-all;
  
  &.editor-name {
    display: inline-block;
    padding: 4px 12px;
    background-color: rgba(66, 139, 202, 0.1);
    border-radius: 4px;
    color: #428bca;
    font-weight: 600;
  }
}

.status-draft {
  color: #c48a10;
  font-weight: 600;
}

.status-pending {
  color: #1890ff;
  font-weight: 600;
}

.status-published {
  color: #21ba45;
  font-weight: 600;
}

.status-deleted {
  color: #d93026;
  font-weight: 600;
}

// 响应式设计
@media (max-width: 1200px) {
  .detail-layout {
    flex-direction: column;
  }
  
  .detail-left,
  .detail-right {
    flex: 1 1 100%;
  }
  
  .detail-right {
    position: static;
  }
}

@media (max-width: 768px) {
  .article-detail-container {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .article-title {
    font-size: 22px;
  }
  
  .article-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .meta-divider {
    display: none;
  }
}
</style>

